package com.ian.common.utils;

import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 张伟
 * @desc
 * @date 2022/1/2 下午10:32
 * @modifier
 */
public class WebUtils {

    public static void out(HttpServletResponse response, String message) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter out = response.getWriter();
        out.write(message);
        out.flush();
        out.close();
    }

    /**
     * 读取request中的body内容
     * @param request
     * @return
     */
    public static JsonNode ReadBodyAsJsonNode(HttpServletRequest request) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return JsonUtils.jsonStrToObject(sb.toString(), JsonNode.class);
    }
}
